package com.hengxinguotong.zhihuichengjian.ui.building;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.BuildFileAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseConstructionAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseUserAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Build;
import com.hengxinguotong.zhihuichengjian.bean.BusinessNotify;
import com.hengxinguotong.zhihuichengjian.bean.BusinessNotifyListRes;
import com.hengxinguotong.zhihuichengjian.bean.Construction;
import com.hengxinguotong.zhihuichengjian.bean.Document;
import com.hengxinguotong.zhihuichengjian.bean.FileBean;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;

/**
 * 质量检查
 * Created by liux on 2017/3/7.
 */

public class BuildTestEnterpriseActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener, BuildFileAdapter.OnClickListener{
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.order_no_tv)
    HXTextView orderNoTv;
    @BindView(R.id.state_tv)
    HXTextView stateTv;
    @BindView(R.id.create_by_tv)
    HXTextView createByTv;
    @BindView(R.id.create_time_tv)
    HXTextView createTimeTv;
    @BindView(R.id.construction_name_tv)
    HXTextView constructionNameTv;
    @BindView(R.id.inspect_date_tv)
    HXTextView inspectDateTv;
    @BindView(R.id.reply_date_tv)
    HXTextView replyDateTv;
    @BindView(R.id.remind_date_tv)
    HXTextView remindDateTv;
    @BindView(R.id.contacts_tv)
    HXTextView contactsTv;
    @BindView(R.id.person_number)
    HXTextView personNumber;
    @BindView(R.id.notice_rv)
    RecyclerView noticeRv;
    @BindView(R.id.test_detail_etv)
    HXTextView testDetailEtv;
    @BindView(R.id.no_data_tv)
    HXTextView noDataTv;
    @BindView(R.id.pic_rv)
    RecyclerView picRv;
    @BindView(R.id.file_rv)
    RecyclerView fileRv;
    @BindView(R.id.main_sl)
    ScrollView mainSl;

    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private List<String> paths;
    private BuildFileAdapter fileAdapter;
    private List<FileBean> fileList;
    private Build build;
    private int type = Constants.LIVE;

    private List<Construction> noticeConstructions;
    private EnterpriseConstructionAdapter noticeEnterpriseAdapter;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    List<BusinessNotify> datas = (List<BusinessNotify>) msg.obj;
                    processNoticers(datas);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", Constants.LIVE);
        setContentView(R.layout.activity_buildtest_enterprise);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        build = (Build) getIntent().getSerializableExtra("build");
        if (build != null) {
            orderNoTv.setText(build.getOrderNo());
            switch (build.getCorrectiveStatus()) {//任务状态1:待回复;2:待复检;3:复检不通过;4:已完成
                case 1:
                    stateTv.setText("待回复");
                    break;
                case 2:
                    stateTv.setText("待复检");
                    break;
                case 3:
                    stateTv.setText("复检不通过");
                    break;
                case 4:
                    stateTv.setText("已完成");
                    break;
            }
            createByTv.setText(build.getCreateName());
            createTimeTv.setText(build.getInspectDate());
            constructionNameTv.setText(build.getConstructionName());
            inspectDateTv.setText(build.getInspectDate());
            replyDateTv.setText(build.getDeadlineReplyDate());
            remindDateTv.setText(build.getWarningReminderDate());
            contactsTv.setText(build.getContactName());

            noticeConstructions = new ArrayList<>();
            noticeEnterpriseAdapter = new EnterpriseConstructionAdapter(this, noticeConstructions);
            noticeEnterpriseAdapter.setOnChildHeadClickListener(headClick);
            noticeRv.setAdapter(noticeEnterpriseAdapter);
            noticeRv.setLayoutManager(getVerticalLinearLayoutManager());
            getEnterpriseUserList(build.getId());//获取企业端告知人列表

            testDetailEtv.setText(build.getItems());
            switch (build.getCorrectiveStatus()){
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
            }
            if((build.getPicList() == null || build.getPicList().size() == 0) && (build.getFileList() == null || build.getFileList().size() == 0)){
                noDataTv.setVisibility(View.VISIBLE);
            }else {
                noDataTv.setVisibility(View.GONE);
                if(build.getFileList() != null && build.getFileList().size() > 0){
                    fileRv.setLayoutManager(getVerticalLinearLayoutManager());
                    fileList = build.getFileList();
                    fileAdapter = new BuildFileAdapter(this, fileList);
                    fileAdapter.setOnClickListener(this);
                    fileRv.setAdapter(fileAdapter);
                }
                if (build.getPicList() != null && build.getPicList().size() > 0) {
                    picRv.setLayoutManager(getHorizontalLinearLayoutManager());
                    paths = build.getPicList();
                    aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                    picRv.setAdapter(aualityTestAddPicAdapter);
                }
            }
        }

        switch (type){
            case Constants.LIVE:
                tvTitleName.setText("任务下发详情");
                break;
        }
    }

    private  EnterpriseUserAdapter.OnChildHeadClickListener headClick = new EnterpriseUserAdapter.OnChildHeadClickListener() {
        @Override
        public void onChildHeadClick(int position, int childPosition) {
            String headPotrait = noticeConstructions.get(position).getUserList().get(childPosition).getHeadPortrait();
            if(!Utils.isEmpty(headPotrait)){
                List<String> picList = new ArrayList<>();
                picList.add(headPotrait);
                TaskBigImgActivity.startActivity(BuildTestEnterpriseActivity.this, (ArrayList<String>) picList, position);
            }
        }
    };

    private LinearLayoutManager getHorizontalLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    private LinearLayoutManager getVerticalLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return linearLayoutManager;
    }

    @OnClick({R.id.iv_back, R.id.contacts_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.contacts_tv:
                break;
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (build != null) {
                TaskBigImgActivity.startActivity(BuildTestEnterpriseActivity.this, (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }
    }

    private void getEnterpriseUserList(String inspectionId) {
        Utils.requestData(null, this, "/build/queryBusinessNotifyByInspectionId/" + SPUtil.getString(this, "uuid") + "?inspectionId=" + inspectionId, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    BusinessNotifyListRes res = new Gson().fromJson(json, BusinessNotifyListRes.class);
                    if(res.getStatus() == 1){
                        List<BusinessNotify> value = res.getValue();
                        Message message = mHandler.obtainMessage();
                        message.what = 0;
                        message.obj = value;
                        message.sendToTarget();
                    }else {
                        showToast(res.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processNoticers(List<BusinessNotify> datas){
        for (BusinessNotify businessNotify:datas){
            Construction construction = new Construction();
            construction.setConstructionName(businessNotify.getConstructionName());
            List<User> userList = construction.getUserList();
            for (String name:businessNotify.getNames()){
                User user = new User();
                user.setName(name);
                userList.add(user);
            }
            noticeConstructions.add(construction);
        }
        noticeEnterpriseAdapter.setDataList(noticeConstructions);
        if(noticeConstructions == null || noticeConstructions.size() <= 0){
            personNumber.setText("无告知人信息");
        }else {
            personNumber.setText("");
        }
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    @Override
    public void onClick(Object o) {
        FileBean fileBean = (FileBean) o;
        if(fileBean == null){
            return;
        }
        Document document = new Document();
        document.setName(fileBean.getName());
        document.setPath(fileBean.getPath());
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        String url = document.getPath().replace("type=2", "type=1");
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(getPackageManager());
            // 打印Log   ComponentName到底是什么
            Log.e("wl", "componentName = " + componentName.getClassName());
            startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            showToast("没有匹配的程序");
        }
    }
}
